﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using BZV.Core.Net;
using System.Threading;

namespace BZV.Foundation.Business
{
    // 管理当前的所有的数据
    public class DataPool:IDisposable
    {
        // 数据集合
        private List<Lottery> m_Lotterys = new List<Lottery>();
        private static string m_strID;
        private static int m_nCount;
        private bool m_bOnLine = false;
        private string m_strPath = "";
        private static List<Lottery> _LotterysOld = new List<Lottery>();
        private static List<Lottery> _LotterysNew = new List<Lottery>();

        public List<Lottery> Lotterys
        {
            get { return m_Lotterys; }
        }

        public void Dispose()
        {
            Save(m_strID + ".txt");
        }

        public static List<Lottery> GetDataOld() { Update(_LotterysOld); return _LotterysOld; }
        public static List<Lottery> GetDataNew() { Update(_LotterysNew); return _LotterysNew; }

        /// <summary>
        /// 构造一个数据池
        /// </summary>
        /// <param name="strID">彩票ID</param>
        /// <param name="nCount">一天的个数</param>
        public DataPool(string strID, int nCount)
        {
            m_strID = strID;
            m_nCount = nCount;
            m_bOnLine = NetHelper.CheckOnLine();

            // 读取文件
            string str = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
            m_strPath = str + "" + strID + ".txt";
            string strFileName = m_strPath;
            if (File.Exists(strFileName))                   // 读取文件
            {
                m_Lotterys = ReadFile(strFileName);

                if (m_bOnLine)
                {
                    List<Lottery> tempLotterys = GetAtIssue(m_strID, m_Lotterys[0].Issue, m_nCount);
                    tempLotterys.RemoveAt(tempLotterys.Count - 1);
                    m_Lotterys.InsertRange(0, tempLotterys);
                }
            }
            else
            {
                m_Lotterys = GetAtCount(strID, 10000, nCount);
            }

            //if (_Lotterys == null)
            {
                if (nCount > 100)
                {
                    _LotterysOld = m_Lotterys;
                }
                else
                {
                    _LotterysNew = m_Lotterys;
                }
                
            }
        }

        public static void Update(List<Lottery> lotterys)
        {
            bool bOnLine = NetHelper.CheckOnLine();
            if (bOnLine)
            {
                List<Lottery> tempLotterys = GetAtIssue(m_strID, lotterys[0].Issue, m_nCount);
                tempLotterys.RemoveAt(tempLotterys.Count - 1);
                lotterys.InsertRange(0, tempLotterys);
            }
        }

        public List<Lottery> ReadFile(string strFileName)
        {
            List<Lottery> lotterys = new List<Lottery>();

            using (StreamReader fs = new StreamReader(strFileName, Encoding.Default))
            {
                string strLine = "";
                while (strLine != null)
                {
                    strLine = fs.ReadLine();
                    if (strLine == null)
                    {
                        continue;
                    }

                    // table分开
                    List<string> strs = new List<string>(strLine.Split('\t'));
                    if (strs.Count <= 1)
                    {
                        continue;
                    }
                    // 期号
                    Lottery lottery = new Lottery();
                    lottery.Create(m_strID, strs[0], strs[1]);
                    lotterys.Add(lottery);
                    
                }
            }

            return lotterys;
        }

        public void Save()
        {
            Save(m_strPath);
        }

        public void Save(string strFileName)
        {
            using (StreamWriter fs = new StreamWriter(strFileName))
            {
                foreach (Lottery lottery in m_Lotterys)
                {
                    string strLine = lottery.Issue + "\t" + lottery.Code;
                    fs.WriteLine(strLine);
                }
            }
        }

        /// <summary>
        /// 获取某一天的数据， 15 01 19 047
        /// </summary>
        /// <param name="strID"></param>
        /// <param name="day"></param>
        /// <param name="nIssueCount">一天的期数（老时时彩120， 新的是84）</param>
        /// <returns></returns>
        public static List<Lottery> GetAtDay(string strID, DateTime day, int nIssueCount = 120)
        {
            // 集合
            List<Lottery> lotterys = new List<Lottery>();
            
            // 获取天的前缀
            string strTime = day.ToString("yyMMdd");

            // 获取彩票信息
            try
            {
                for (int i = 1; i <= nIssueCount; i++)
                {
                    string strIssue = strTime + string.Format("{0:D3}", i);
                    Lottery lottery = Query.QueryLottery(strID, strIssue);
                    if (lottery.Code != "")
                    {
                        lotterys.Add(lottery);
                    }
                }
            }
            catch (System.Exception ex)
            {
                return null;
            }
            

            return lotterys;
        }

        /// <summary>
        /// 获取最近的指定的条数的信息
        /// </summary>
        /// <param name="strID"></param>
        /// <param name="nCount"></param>
        /// <param name="nIssueCount">一天的期数（老时时彩120， 新的是84）</param>
        /// <returns></returns>
        public static List<Lottery> GetAtCount(string strID, int nCount, int nIssueCount = 120)
        {
            // 集合
            List<Lottery> lotterys = new List<Lottery>();

            // 获取当前的期数
            StartTime startTime = Query.QueryStartTime(strID);
            string strNo = startTime.strIssue.Substring(6, 3);
            int nNo = Convert.ToInt32(strNo);
            nNo--;

            // 开始获取彩票
            DateTime time = DateTime.Now;
            do
            {
                // 当天的查询完成，就查前一天的
                if (nNo == 0)
                {
                    nNo = nIssueCount;
                    time = time.AddDays(-1);
                }

                // 开始查询
                string strTime = time.ToString("yyMMdd");
                string strIssue = strTime + string.Format("{0:D3}", nNo);
                Lottery lottery = Query.QueryLottery(strID, strIssue);
                if (lottery == null)
                {
                    nNo--;
                    continue;
                }

                if (lottery != null && lottery.Code != "")
                {
                    lotterys.Add(lottery);
                    nNo--;
                }

            } while ((--nCount) != 0);
            

            return lotterys;
        }

        /// <summary>
        /// 获取指定期号之前的所有彩票
        /// </summary>
        /// <param name="strID"></param>
        /// <param name="strIssue"></param>
        /// <param name="nIssueCount"></param>
        /// <returns></returns>
        public static List<Lottery> GetAtIssue(string strID, string strIssue, int nIssueCount = 120)
        {
            // 集合
            List<Lottery> lotterys = new List<Lottery>();

            // 获取当前的期数
            StartTime startTime = Query.QueryStartTime(strID);
            string strNo = startTime.strIssue.Substring(6, 3);
            int nNo = Convert.ToInt32(strNo);
            nNo--;

            // 开始获取彩票
            DateTime time = DateTime.Now;
            Lottery lottery;
            do
            {
                // 当天的查询完成，就查前一天的
                if (nNo == 0)
                {
                    nNo = nIssueCount;
                    time = time.AddDays(-1);
                }

                // 开始查询
                string strTime = time.ToString("yyMMdd");
                string issue = strTime + string.Format("{0:D3}", nNo);
                lottery = Query.QueryLottery(strID, issue);
                if (lottery == null)
                {
                    nNo--;
                    lottery = new Lottery();
                    continue;
                }

                if (lottery != null && lottery.Code != "")
                {
                    lotterys.Add(lottery);
                    nNo--;
                }

            } while (lottery.Issue != strIssue);

            return lotterys;
        }
    }

    public class UpdateThread1
    {
        private DataPool m_dataPool = new DataPool("255401", 120);
        private System.Timers.Timer m_TickTimer = new System.Timers.Timer();
        private Thread thread;
        private bool m_bInUse;

        public UpdateThread1()
        {
            //thread = new Thread(m_dataPool.Update);
            m_bInUse = false;
        }

        public void StartUpdate()
        {
            if (!m_bInUse)
            {
                m_TickTimer.Interval = 10 * 1000;
                m_TickTimer.Elapsed += new System.Timers.ElapsedEventHandler(Timers_Timer_Elapsed);
                m_TickTimer.Enabled = true;
                m_TickTimer.Start();
                m_bInUse = true;
            }
        }

        public void StopUpdate()
        {
            m_TickTimer.Enabled = false;
            m_TickTimer.Stop();
            m_bInUse = false;
        }

        private void Timers_Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            // 将数据保存
            m_dataPool.Save();
            //m_dataPool.Update();
        }
    }


    public class UpdateThread
    {
        private DataPool m_dataPool = new DataPool("255401", 120);
        private System.Timers.Timer m_TickTimer = new System.Timers.Timer();
        private Thread thread;
        private bool m_bInUse;

        public UpdateThread()
        {
            //thread = new Thread(m_dataPool.Update);
            m_bInUse = false;
        }

        public void Update()
        {
            while(m_bInUse)
            {
                //m_dataPool.Update();
                Thread.Sleep(10 * 1000);
            }
        }

        public void StartUpdate()
        {
            m_bInUse = true;
            //thread.Start();
        }

        public void StopUpdate()
        {
            m_bInUse = false;
            m_dataPool.Save();
        }

        private void Timers_Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            // 将数据保存
            m_dataPool.Save();
            //m_dataPool.Update();
        }
    }
}
